我有 3 個字串。我需要從這 3 個字串中創建一個陣列,當我這樣做時,它會向我顯示字串的記憶體地址與陣列的記憶體地址不同。這意味著他們不指向同一件事。但是我希望,如果我在創建陣列后更改了創建陣列的字串,那么陣列將自動更新。反之亦然。這可能嗎,我該怎么做。這是我的代碼,表明它們不使用相同的記憶體地址,因此,它們不一樣:
std::string x = "x";
std::string y = "y";
std::string z = "z";
std::string letters[3] = {x, y, z};
std::cout << &x << "\t" << &y << "\t" << &z << "\n";
std::cout << &letters[0] << "\t" << &letters[1] << "\t" << &letters[2] << "\n";
輸出是:
0x20b1bff730 0x20b1bff710 0x20b1bff6f0
0x20b1bff690 0x20b1bff6b0 0x20b1bff6d0
uj5u.com熱心網友回復:
在這個陣列的宣告中
std::string letters[3] = {x, y, z};
初始化器被復制到陣列的元素中,
所以用作初始化器的字串和存盤在陣列中的字串是不同的物件。
您可以宣告一個型別的陣列,std::reference_wrapper例如
#include <utility>
#include <string>
//...
std::reference_wrapper<std::string> letters[] = { std::ref( x ), std::ref( y ), std::ref( z ) };
這是一個演示程式。
#include <iostream>
#include <string>
#include <utility>
int main( int argc, char * argv[] )
{
std::string x = "x";
std::string y = "y";
std::string z = "z";
std::reference_wrapper<std::string> letters[] =
{
std::ref( x ), std::ref( y ), std::ref( z )
};
for (const auto &r : letters)
{
std::cout << r.get() << ' ';
}
std::cout << '\n';
x = "u";
y = "v";
z = "w";
for (const auto &r : letters)
{
std::cout << r.get() << ' ';
}
std::cout << '\n';
}
程式輸出為
x y z
u v w
uj5u.com熱心網友回復:
所以這里有一些使用指標的代碼,這就是你想要的
std::string* xp = new std::string("x");
std::string* yp = new std::string("y");
std::string* zp = new std::string("z");
std::string* letters[3] = { xp, yp, zp };
*xp = "X"; // changes *xp and *letters[0], since xp == letters[0]
現在原始指標是一個壞主意,所以上面應該使用智能指標撰寫
#include <memory>
std::shared_ptr<std::string> xp = std::make_shared<std::string>("x");
std::shared_ptr<std::string> yp = std::make_shared<std::string>("y");
std::shared_ptr<std::string> zp = std::make_shared<std::string>("z");
std::shared_ptr<std::string> letters[3] = { xp, yp, zp };
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/525552.html
標籤:C 数组细绳c 11指针
上一篇:如何用gcc設定`rpath`?
