.*操作符在c++中做什么?
visual What does .* operator do in C++?
a.*b运算符在c++中做什么?我找到了这个参考资料:"对象a的成员b指向的对象",但在下面的例子中不起作用:
class Color {
public:
int red,green,blue;
Color():red(255), green(255), blue(255){}
Color(int red, int green, int blue) :red(red), green(green), blue(blue){}
void printColor(){
cout << "Red:" << red << " Green:" << green << " Blue:" << blue << endl;
}
};
class Chair{
public:
Color* color;
private:
int legs;
float height;
public:
Chair(int legs, float height):legs(legs), height(height){
color = new Color(255, 0 , 0);
}
void printChair(){
cout << "Legs: " << getLegs() << " , height: " << getHeight() << endl;
}
int getLegs() { return legs; }
float getHeight(){ return height; }
Chair& operator+(Chair& close_chair){
this->legs += close_chair.getLegs();
this->height += close_chair.getHeight();
return *this;
}
};
int main(){
Chair my_chair(4, 1.32f);
my_chair.*color.printColor();
return 0;
}
当我使用my_chair.*color.printColor();在main中,我得到'color':未声明的标识符。我在Visual Studio中运行这个例子。
谢谢。
.*
是解引用一个指向成员的指针,但您只是想解引用一个成员指针。为此,使用->
:
my_chair.color->printColor();
(*(my_chair.color)).printColor(); //same thing
在你的例子中使用.*
看起来像:
auto colorP = &Chair::color;
(my_chair.*colorP)->printColor();
如果您想取消对color
成员的引用,请执行以下操作:
my_chair.color->printColor();
或
(*my_chair.color).printColor();
操作符.*
解引用指向成员的指针。
指向成员的指针——"成员指针"——不同于成员是指针。
它不指向类的特定实例,所以你需要一个与"指针"相关的实例。
的例子:
struct A
{
int x;
int y;
};
int main()
{
A a{1, 78};
// Get a pointer to the x member of an A
int A::* int_member = &A::x;
// Prints a.x
std::cout << a.*int_member << std::endl;
// Point to the y member instead
int_member = &A::y;
// Prints a.y
std::cout << a.*int_member << std::endl;
}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 我应该使用什么来代替void作为变体中的替代类型之一
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用