0

I'm trying to write to variables 1 and 2 in Class3 from Class1.

I don't have any problem writing to any variable in Class2 from Class1. However, I can't seem to permanently write to a Class3 variable from Class1. I know they're receiving the right values because a cout within the read() method, after the assignments, will print the correct values. However, that same cout pasted into the print() method will not print the new values. It seems as though their getting temporarily written...

Sorry for the class madness

class Class1
{
public:
  Class1();
private:
  Class2 *myClass2Array;
};

Class1::Class1()
{
  myClass2Array = new Class2[size];
  myClass2Array[i].getArray(myClass2Array[i].getCount()).read(string1, string2); // this line is probably a problem
}

So, the constructor for Class1 is trying to call read() that's in Class3, which is declared in Class2...

class Class2
{
public:
  Class2();
  int getCount();
  Class3 getArray(int i) { return myClass3Array[i]; }
private:
  Class3 *myClass3Array;
  int count;
}; 

Class2::Class2()
{
  count = 0;
  myClass3Array = new Class3[8];
}

I've also tried Class3 myClass3Array[8]; and initializing each one in a for loop... Here's Class3

class Class3
{
  string var1;
  string var2;
public:
  Class3();
  void print();
  void read(string, string);
}; 


Class3::Class3()
{
  var1 = "";
  var2 = "";
}

void Class3::print()
{
  cout << var1 << " and " << var2 << endl; // will print old, initiated values
} // end function print()

void Class3::read(string string1, string string2)
{
  var1 = string1;
  var2 = string2;
  cout << var1 << " " << var2 << endl; // will print new values
} // end function read()

I'm guess my problem is either in the way I declared the array, or in how I'm trying to access (write to) it. Any ideas?

4

1 回答 1

1

问题是您的Class2::getArray方法正在返回一个副本。

更改它以返回参考

Class3& getArray(int i) { return myClass3Array[i]; }

问题是您正在设置对象副本的值Class3,而不是对象中的原始Class2值。这就是为什么你的价值观不坚持的原因。

另一种方法是添加一个 setArray 方法

void setArray(int i, const Class3& a) { myClass3Array[i] = a; }

然后

Class3 c3;
c3.read(string1, string2);
myClass2Array[i].setArray(myClass2Array[i].getCount(), c3);
于 2013-05-06T05:06:29.903 回答