我正在将子对象解析为方法,但我的子数据丢失了。请告诉我如何在不丢失数据的情况下解析对象。
class A
{
int size;
std::string name;
public:
A(const std::string &name, int &size){}
virtual B *C();
}
function D()
{
int size = 10;
std::string name = "name";
return new A(name , size);
}
B *A::C(){
\\here I need name and size
}
现在写下它给出的大小的值是0而不是10,对于名称,它给出了分段错误
感谢4提前帮助
更新1 我的代码摘要
class PrototypeAST
{
int size;
std::string FnName;
std::vector<std::string> ArgNames;
public:
PrototypeAST(const std::string &fnName, const std::vector<std::string> &argNames, int &size)
: FnName(fnName), ArgNames(argNames) {}
Function *Codegen();
void CreateArgumentAllocas(Function *F);
};
static PrototypeAST *ParsePrototype() {
int size;
std::string FnName = IdentifierStr;
getNextToken();//eat id1
std::vector<std::string> ArgNames;
if(CurTok != ')' )
{
getNextToken(); //eat int
ArgNames.push_back(IdentifierStr);
getNextToken();// eat id
while (CurTok == ',')
{
getNextToken(); //eat ,
getNextToken(); //eat int
ArgNames.push_back(IdentifierStr);
getNextToken();// eat id
}
}
// success.
getNextToken(); // eat ')'.
size = ArgNames.size();
return new PrototypeAST(FnName, ArgNames, size);
}
Function *PrototypeAST::Codegen() {
printf("\nI am in prototypeAST function\n");
// Make the function type: double(double,double) etc.
std::vector<Type*> Doubles(size,
Type::getInt1Ty(getGlobalContext()));
printf("\nI am in prototypeAST function's 1\n");
FunctionType *FT;
if(isFunInt)
FT = FunctionType::get(Type::getInt1Ty(getGlobalContext()),
Doubles, false);
else if(isFunVoid)
FT = FunctionType::get(Type::getInt1Ty(getGlobalContext()),
Doubles, false);
printf("\nI am in prototypeAST function's 2\n");
Function *F = Function::Create(FT, Function::ExternalLinkage, FnName, TheModule);
printf("\nI am in prototypeAST function's 3\n");
// If F conflicted, there was already something named 'Name'. If it has a
// body, don't allow redefinition or reextern.
if (F->getName() != FnName) {
// Delete the one we just made and get the existing one.
F->eraseFromParent();
F = TheModule->getFunction(FnName);
}
// Set names for all arguments.
unsigned Idx = 0;
for (Function::arg_iterator AI = F->arg_begin(); Idx != ArgNames.size();
++AI, ++Idx) {
AI->setName(ArgNames[Idx]);
}
printf("\nI am in prototypeAST function\n");
return F;
}
答案 0 :(得分:1)
正如其他人在评论中指出的那样,你应该看看空构造函数。您没有在构造函数中设置数据成员的值。这就是错误的原因。
PS:熟悉Stack Overflow问题清单。快乐学习。
答案 1 :(得分:0)
我有你想做的事。这是实现它的方法。
空构造函数正在解决问题。您可以通过以下方式使用函数返回值初始化参数。
class A
{
int Size;
std::string Name;
public:
A(const std::string &name, int &size):Name(name), Size(size) {}
virtual B *C();
}
A *D()
{
int size = 10;
std::string name = "name";
return new A(name , size);
}
B *A::C(){
\\here I need name and size
}