我有一个包含多个实例的类。我也有全球功能。我想在我班上访问一个变量。但是,我得到一个错误,我无法从静态对象访问非静态引用。有解决办法吗?
在一个文件中我会有这样的东西:
Public class A{
public: int angle;
}
在另一个文件中,我可能会有这样的事情:
#include "A.h"
void changeAngle()
{
A.angle = 5;
}
答案 0 :(得分:1)
访问非静态引用意味着您正在尝试访问对象的属性。要做到这一点,你必须有一个对象:
#include <iostream>
#include <string>
class T
{
public:
std::string s;
static const std::string t;
T () : s("hey") {}
const std::string& getS()
{
return s;
}
static void function()
{
// You need an object
T t;
// To access a non-static reference, from anywhere.
std::cout << t.getS() << std::endl;
}
};
const std::string T::t = "ho";
int main(int argc, const char *argv[])
{
// You don't need an object to call a static member funciton.
T::function();
// Or to access a static attribute.
std::cout << T::t << std::endl;
return 0;
}
输出:
hey
ho