I can't access the variable width .
The Ah file:
namespace AN{
template <typename T> class A{
public:
unsigned int width; #The variable
...
}
}
The B.cpp file:
#include "A.h"
using namespace AN;
namespace BN{
bool something(){
unsigned int * w = AN::&width;
}
}
I tried also AN::A::&width but it doesn't work as well.
This has nothing to do with templates. It's about classes and objects. The address of width
is determined by the object that it's a part of; without an object, there is no width.
However, without an object you can create a pointer-to-member; it's not an ordinary pointer (if it was, it would be called "pointer"). Like this:
class A {
public:
int width;
};
int A::*w = &A::width;
You use it to access that variable when you create an object:
A a;
a.*w = 3;
A aa;
aa.*w = 4;
If you really only want one value of width
for every object of your type, yes, you can make it a static
member:
class A {
public:
static int width;
};
int A::width;
Now you can create a pointer to that member as an ordinary pointer:
int* w = &A::width;
and you can use w
as an ordinary pointer:
*w = 3;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.