#include <iostream> #include <string> int main() { std::string str = "abcdef"; std::size_t i = 1; std::cout << str[i] << std::endl; std::cout << &str[i] << std::endl; return 0; }
において、 std::cout << &str[i] << std::endl;の&str[i] はアドレスを扱うと思っていたのですが、Cでは&str[i] はアドレスを扱うのにC++では&str[i] はアドレスではなく文字や文字列を扱うのでしょうか?
ちなみに、Cのように以下のプログラムのようにC++で一文字だけ扱うように書くにはどう書けばいいのでしょうか?
char* p, * q; int ch; ch = *q;
また、こちらのプログラムは実行してもエラーが起きるのですが、何が原因なのでしょうか?
#include <iostream> #include <string> int main() { std::string str = "abcdef"; std::size_t i = 1; std::cout << *(str + i) << std::endl; std::cout << (str + i) << std::endl; std::cout << &*(str + i) << std::endl; return 0; }
Hey, stop it!
Don't open the door to C++ yet.
No one can use std::string without understanding "char", "array of char", "pointer", and other basics of C.
This is really serious advice!!
> こちらのプログラムは実行してもエラーが起きるのですが
そもそも、コンパイルに成功するのですか?
(paiza.ioに投げてみたらコンパイルに失敗しましたので、「実行してのエラー」を確認することはできませんでした)
> こちらのプログラムは実行してもエラーが起きるのですが、何が原因なのでしょうか?
コンパイルすら失敗します。実行できません。
https://oshiete.goo.ne.jp/qa/12485681.html
何か微妙に変えてるけど、向こうの人コードべた書きなのによく読めるな。