【发布时间】:2015-08-09 21:40:52
【问题描述】:
我正在尝试学习 C++,但有一个关于在 C++ 中返回数组的问题。我知道在这种情况下,Vector 可能会更好,并且不需要 getter 方法,因为字段在同一个类中是可见的,但我正在尝试学习内存管理,所以我会使用它们。
class Color {
double r;
double g;
double b;
public:
Color(int a, int aa, int aaa) {
r = a;
g = aa;
b = aaa;
}
bool operator==(const Color &other) {
double *otherCol = other.getter();
return otherCol[0] == r && otherCol[1] == g && otherCol[2] == b;
}
double* getter() const {
double second[3] = {r,g,b};
return second;
}
};
int main() {
Color col1(23, 54, 200);
Color col2(23, 54, 200);
cout << (col1 == col2) << endl;
return 0;
}
如果 RGB 颜色相同,此代码应打印 1,否则打印 0。但它不会打印 1。为了调试,我在 operator== 的 return 语句之前添加了以下几行(故意两次):
cout << otherCol[0] << " " << otherCol[1] << " " << otherCol[2] << endl;
cout << otherCol[0] << " " << otherCol[1] << " " << otherCol[2] << endl;
奇怪的是,结果不一样:
23 54 200
6.91368e-310 6.91368e-310 3.11046e-317
谁能告诉我这是什么原因造成的,什么是不依赖于 Vector 或动态内存分配的合理补救措施?假设我们不想将数组传入getter() 进行更新。
【问题讨论】:
标签: c++ arrays memory-management