指向具有函数C++的数据成员的指针
Pointer to Data Members with functions C++
#include "stdafx.h"
#include <iostream>
using namespace std;
class thing{
public:
int stuff, stuff1, stuff2;
void thingy(int stuff, int *stuff1){
stuff2=stuff-*stuff1;
}
}
int main(){
thing t;
int *ptr=t.stuff1;
t.thingy(t.stuff, *ptr);
}
我一直在练习课程,并在C++中指点。我想做的是让函数 thingy 通过传递指向 stuff1 值的指针来修改 thing 类中的 stuff2 数据成员。我该怎么做?
您正在创建一个 pointer-to-int 类型的变量: 如果你想要一个指向t.stuff1
的指针,取它的地址:
int* ptr = &t.stuff1;
___^ here you are taking a reference (address)
然后,将该指针传递给thing::thingy
方法:
t.thingy(t.stuff, ptr);
__^ don't dereference the pointer, your function takes a pointer
试试这个:
int *ptr;
*ptr = t.stuff1;
t.thingy( t.stuff, ptr);
我可能真的迟到了,但我想得到一些好的评论和测试
//#include "stdafx.h"
#include <iostream>
using namespace std;
//class declaration
class thing{
public:
int stuff, stuff1, stuff2;
thing(){//constructor to set default values
stuff = stuff1 = stuff2 = 10;
}
void thingy(int param1, int *param2){
stuff2=param1-*param2;
}
};
//driver function
int main(){
thing t;//initialize class
cout << t.stuff << ' ' << t.stuff1 << ' ' << t.stuff2 << endl;//confirm default values
int *ptr= &t.stuff1;//set the ADDRESS (&) of stuff1 to an int pointer
cout << *ptr << endl;
t.thingy(t.stuff, ptr); //call function with pointer as variable
cout << t.stuff1;
}
int *ptr=t.stuff1;
无法将 int 转换为 int*t.stuff1 是一个 int 值,而不是 int 的指针试试这个:
int *ptr=&t.stuff1;
你应该在类定义的末尾添加 ";",如下所示:
class Thing {
...
};
当你调用 t.thingy 时,第二个参数是 int*但是 *ptr 是一个 int 值,而不是指针。PTR 是一个指针,而不是 *PTR。试试这个:
t.thingy(t.stuff, ptr);
你应该知道:
int i_value = 1;
int* p_i = &i_value;
int j_value = *p_i;
在这种情况下:i_value j_value *p_i 的类型为 intp_i的类型为 int*
你应该传递地址:
*ptr = &(t.stuff1);
相关文章:
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 使用指针访问数组中的对象数据成员
- 共享 C++ 的数据成员指针
- C++数据成员:值与指针
- 如何使用数据成员填充派生类的对象到基类的指针数组中
- 如何在C++中使用类对象访问指针数据成员
- 将指向数据成员的指针传递给 std::invoke 时有哪些用例和有用性?
- 通过指针算法访问结构数据成员
- 如何强制实施有关指针数据成员的常量正确性
- 类数据成员指针的非类型模板参数包无法使用 gcc 编译
- constexpr 偏移量,带有指向成员数据的指针
- 指向未由对象地址初始化的对象的指针如何将值分配给类的数据成员
- 将数据成员的指针传递给基类构造函数是否安全?
- 虚拟指针大小因类数据成员而异
- "new"不会将内存分配给作为类的数据成员的指针
- 关于Lambdas,转换以功能指针以及私人数据成员的可见性
- 向上转换指向数据成员及其多态行为的指针
- 指向数据成员转换的 Constexpr 指针
- 关于C++中指向数据成员的指针的一些混淆
- C 细分故障访问类数据成员,而无需明确使用指针