【发布时间】:2019-04-27 16:27:49
【问题描述】:
我在从另一个类(B 类)函数调用一个类(A 类)函数时遇到问题,我尝试调用的类(A 类)的变量在该类中构造后被删除该函数完成并返回到我从中调用的函数(C类)。发生了什么,我该如何解决?
我尝试使用指向该类的指针并动态分配整个类,但变量仍然被删除。
#include <iostream>
#include <vector>
#include <string>
#include <ctime>
using namespace std;
class A {
private:
vector<string> vectorA;
string stringA[5] = { "1", "2", "3", "4", "5" };
string stringB[5] = { "6", "7", "8", "9" };
public:
string generaterandnum() {
int num1 = NULL;
num1 = rand() % vectorA.size();
string card = vectorA[num1];
vectorA.erase(vectorA.begin() + num1);
return card;
}
void buildvectorA()
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
vectorA.push_back(stringA[j] + stringB[i]);
}
}
return;
}
};
class B {
private:
vector<string> vectorB;
vector<string> vectorC;
A aobject;
public:
void buildvectorBandC() {
for (int i = 0; i < 5; i++) {
vectorB.push_back(aobject.generaterandnum());
}
for (int i = 0; i < 5; i++) {
vectorC.push_back(aobject.generaterandnum());
}
}
void displayvector() {
cout << "Vector: ";
for (size_t i = 0; i < vectorB.size(); i++) {
cout << "[" << vectorB[i] << "] (" << i << ") ";
}
cout << endl;
}
};
class C {
friend int main();
void programrun(int option) {
A* a = new A;
a->buildvectorA();
B* b = new B;
if (option == 0) {
cout << "Here is the vector that just has been constructed" << endl;
b->buildvectorBandC();
while (true) {
b->displayvector();
}
}
}
};
int main() {
srand((unsigned int)time(NULL));
cout << "Hello" << endl;
cout << "Enter (R) to run the program." << endl;
char input;
while (true) {
cin >> input;
input = toupper(input);
if (input == 'R') {
C cobject;
cobject.programrun(0);
return false;
}
else {
cout << "Invalid input" << endl;
}
}
}
我希望用随机生成的数字构建向量 B 和 C,这些数字从向量 A 中挑选变量。但我得到的是,当它到达 generaterandnum() 时,它显示一个错误,说 Project1.exe 中 0x00F1C77F 处的未处理异常:0xC0000094:整数除以零。因为vectorA的大小为0,因为它在程序离开该类的范围后被删除了。
【问题讨论】:
-
你想要
new并在堆上分配对象,如果你想让它们比作用域长。请不要使用原始的new;使用智能指针。 -
这里只是吹毛求疵,但
NULL用于空指针(继承自C)。 C++ 没有“空”值的概念。 -
您的错误是认为非静态数据成员属于一个类。这不是真的。类的每个实例都有自己的所有非静态数据成员的独立副本。 (事实上,这就是
static和非静态数据成员之间的全部区别) -
我之前遇到过静态成员的问题。如果我将某些东西变成静态成员,我将不得不将我的整个程序变成静态成员变量和函数,在类之外声明它们,这使得类无用。
标签: c++ class object dynamic-memory-allocation calling-convention