-2
我寫了矢量類,但是當我在我的主體中打印對象時,它會打印出值的地址,爲什麼? 非常感謝您的幫助。C++ - 使用指針,打印地址而不是值,爲什麼? (使用運算符)
Vector.header:
#include <iostream>
class Vector{
private:
int* first;
int* second;
public:
Vector();
Vector(int num1, int num2);
~Vector();
Vector(Vector& other);
int* getFirst();
void setFirst(int* first);
int* getSecond();
void setSecond(int* second);
void print();
const Vector& operator=(const Vector& other){
first = other.first;
second = other.second;
return *this;
}
Vector operator++(){
return Vector(*first + 1, *second + 1);
}
Vector operator--(){
return Vector(*first - 1, *second - 1);
}
};
Vector::Vector(){
first = 0;
second = 0;
}
Vector::Vector(int num1, int num2){
first = &num1;
second = &num2;
}
Vector::~Vector(){
}
Vector::Vector(Vector& other) : first(other.first), second(other.second){}
int* Vector::getFirst(){
return first;
}
void Vector::setFirst(int* f){
first = f;
}
int* Vector::getSecond(){
return second;
}
void Vector::setSecond(int* s){
second = s;
}
void Vector::print(){
std::cout << "<" << getFirst() << "," << getSecond() << ">" << std::endl;
}
main.cpp中:
#include <iostream>
#include "Vector.h"
int main(){
Vector* v1 = new Vector(2, 3);
Vector* v2 = new Vector(5, 6);
v1++;
v2--;
v1->print();
v2->print();
system("pause");
return 0;
}
打印我:
<FDFDFDFD,ABABABAB>
<0000008F,FDFDFDFD>
感謝的對你有所幫助........
打印指針值時您期望什麼?你的意思是使用'*'解引用它們嗎? –
歡迎來到Stack Overflow。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –
您的構造函數'Vector(int num1,int num2)'存儲構造函數退出時超出範圍的臨時變量的地址。解除引用'first'或'second'將是UB。你不能在你的構造函數中執行'first = &num1;'或'second = &num2;'。 – drescherjm