主函数中的 C++ 私有变量访问
C++ private variable access in main function
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Movie{
string title;
string genre;
int rating;
public:
Movie(string t, string g);
void printDetail();
};
Movie :: Movie(string t, string g){
title = t;
genre = g;
rating = rand()%10;
}
void Movie :: printDetail(){
cout <<" Title : " <<title<<endl;
cout <<" Genre : " <<genre<<endl;
cout <<" Rating : " <<rating<<endl;
}
在 main
我有以下内容:
int main()
{
Movie M[5]={
Movie("The Avengers","Action"),
Movie("Infinity War","Action"),
Movie("Gupigain Baghabain","Comedy"),
Movie("Anonymous 616","Horror"),
Movie("Sara's Notebook","Thriller")
};
for(int i=0;i<5;i++){
cout <<" "<<i+1<<".";
M[i].printDetail();
cout<<endl;
}
M[0].rating; // Here i need to access to rating...!!
// Here I need to compare which movies rating is highest..!!
// So I need to access rating variable...!!
// But how can I do this...!!
// There has a condition... That is I can't declare any other member function..!!!
}
在这里我要显示哪个评分最高哪个评分最低..!!
将此添加到 class:
bool isHighest(Movie otherMovie){
return rating > otherMovie.rating;
}
如果需要,可以将其设为运算符:
bool operator >(Movie otherMovie){
return rating > otherMovie.rating;
}
您可以使 getter 和 setter 函数间接访问私有成员
还有另一个不标准的 hack:将私有成员的 offest 获取到 class 头部,然后获取 class 的地址并将 offest 添加到它,因此您拥有私有地址会员,可以直接访问
这不受标准 c++ 支持,您需要自己进行计算,在您的情况下并不困难
当您想从 dll 中获取结构或 class 以获取特定成员的值并且您没有结构的定义但您可以使用从 dll 中获取 rva offest 时,可以使用此方法各种方法,如反汇编 dll 的某些字节
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Movie{
string title;
string genre;
int rating;
public:
Movie(string t, string g);
void printDetail();
};
Movie :: Movie(string t, string g){
title = t;
genre = g;
rating = rand()%10;
}
void Movie :: printDetail(){
cout <<" Title : " <<title<<endl;
cout <<" Genre : " <<genre<<endl;
cout <<" Rating : " <<rating<<endl;
}
在 main
我有以下内容:
int main()
{
Movie M[5]={
Movie("The Avengers","Action"),
Movie("Infinity War","Action"),
Movie("Gupigain Baghabain","Comedy"),
Movie("Anonymous 616","Horror"),
Movie("Sara's Notebook","Thriller")
};
for(int i=0;i<5;i++){
cout <<" "<<i+1<<".";
M[i].printDetail();
cout<<endl;
}
M[0].rating; // Here i need to access to rating...!!
// Here I need to compare which movies rating is highest..!!
// So I need to access rating variable...!!
// But how can I do this...!!
// There has a condition... That is I can't declare any other member function..!!!
}
在这里我要显示哪个评分最高哪个评分最低..!!
将此添加到 class:
bool isHighest(Movie otherMovie){
return rating > otherMovie.rating;
}
如果需要,可以将其设为运算符:
bool operator >(Movie otherMovie){
return rating > otherMovie.rating;
}
您可以使 getter 和 setter 函数间接访问私有成员 还有另一个不标准的 hack:将私有成员的 offest 获取到 class 头部,然后获取 class 的地址并将 offest 添加到它,因此您拥有私有地址会员,可以直接访问 这不受标准 c++ 支持,您需要自己进行计算,在您的情况下并不困难 当您想从 dll 中获取结构或 class 以获取特定成员的值并且您没有结构的定义但您可以使用从 dll 中获取 rva offest 时,可以使用此方法各种方法,如反汇编 dll 的某些字节