所以我得到了這個Exception
,我知道這只是因爲我是新來的C++和我的代碼是錯誤的(所以,不,這不是一個已經問過的問題)。在cout上的System.AccessViolationException << line
我得到了Frog.cpp
文件和program.cpp
文件。
Frog.cpp:
#include <iostream>
#include <conio.h>
#include "Frog.h"
using namespace std;
Frog::Frog()
{
(*this).status = Free;
(*this).color = "Green";
(*this).weight = 200; // In grams
}
Frog::Frog(float weight, int age, char* color, char* nickname, Status status)
{
(*this).weight = weight;
(*this).age = age;
(*this).color = color;
(*this).nickname = nickname;
(*this).status = status;
}
Frog::Frog(float weight, int age)
{
(*this).weight = weight;
(*this).age = age;
}
void Frog::currentState()
{
cout << "Weight:" << (*this).weight << " ,Age:" << (*this).age << " ,Color:" << (*this).color << " , Nickname:" << (*this).nickname << " , Status:" << (*this).status << endl; // The ling that causeing the mayhem
}
Frog.h:
#ifndef FROG_H
#define FROG_H
typedef enum Status { Free, Urban, Plate, Dead };
class Frog
{
private:
float weight;
int age;
char* color;
char* nickname;
Status status;
public:
Frog();
Frog(float weight, int age, char* color, char* nickname, Status status);
Frog(float weight, int age);
void currentState();
};
#endif
Program.cpp:
#include <iostream>
#include <conio.h>
#include "Frog.h"
using namespace std;
void main()
{
Frog frog = Frog();
frog.currentState(); // I get the Exception on this line
getch();
}
除外:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at std.char_traits<char>.length(SByte* _First) in c:\program files (x86)\microsoft visual studio 12.0\vc\include\iosfwd:line 523
at std.operator<<<struct std::char_traits<char> >(basic_ostream<char\,std::char_traits<char> >* _Ostr, SByte* _Val) in c:\program files (x86)\microsoft visual studio 12.0\vc\include\ostream:line 791
at Frog.currentState(Frog*)
壞線cout << "Weight:" << (*this).weight << " ,Age:" << (*this).age << " ,Color:" << (*this).color << " , Nickname:" << (*this).nickname << " , Status:" << (*this).status << endl;
在Frog.cpp
。
任何建議將不勝感激。
OT:對於任何指針「foo」,您都可以寫'foo-> bla'而不是'(* foo).bla'。 (也有幾個非指針)。 –
你不檢查的綽號是有效的,並沒有將其設置爲默認的構造函數的默認值。試圖打印一個不指向有效c字符串的const char *是一個不同的錯誤計劃。 – jaggedSpire
邊注:請使用類初始化列表(和替換(*此)這個 - >) –