[英]How to set a member variable from outside of class and make use of that varible inside class in C++ ?
我对cocos2dx和c ++也很陌生。 我在类之间传递数据时遇到问题。
这是我的问题
我有一个class1,其中我需要设置变量的值并调用另一个类的函数,我们称“ Class2”。
我需要在class1中执行此操作,而无需创建class2的对象。
到目前为止,我所做的如下。
Class1.cpp
#include "class2.h"
void Class1::methodinClassOne()
{
class2::imageName = this->str;
class2::doSth();
}
class2.h
class class2 {
public:
std::string imageName;
static void doSth();
};
class2.mm
#include "class2.h"
using namespace cocos2d;
void class2::doSth() {
id sth = [[UIApplication sharedApplication] delegate];
if ([sth isKindOfClass:[AppController class]])
{
printf("class2::doSth imageName %s",imageName.c_str());
SpriteVC *SPVC = [[SpriteVC alloc] initWithNibName:nil bundle:nil];
SPVC.imageNameString = [NSString stringWithFormat:@"%s",imageName.c_str()];
NSLog(@"class2::doSth imageName == %@",[NSString stringWithFormat:@"%s",imageName.c_str()]);
SPVC.imageView.frame = CGRectMake(480, 320, 333, 333);
AppController *controller = (AppController *)sth;
[controller.viewController.view addSubview:SPVC.imageView];
}
}
错误如下
在class2.h内部,我也尝试使用
static std::string imageName;
代替
std::string imageName;
但这给了我以下错误
Undefined symbols for architecture i386:"class2::imageName", referenced from:class2::doSth() in XBridge.o
我知道我在这里缺少C ++的一个非常基本的概念。 但似乎找不到什么错。 请帮我在这里。 谢谢
除了声明之外,还必须在类主体之外定义静态成员变量。 因此,首先,必须在class2
头文件中将成员变量imageName
声明为静态,然后还必须在相应的mm文件中定义变量:
class2.h
class class2 {
public:
static std::string imageName;
static void doSth();
};
class2.mm
#include "class2.h"
std::string class2::imageName;
//other stuff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.