注册 登录
编程论坛 C++教室

帮小女子看看这简单的C++类程序,有一句不明白

avator123 发布于 2011-12-31 11:48, 832 次点击
程序代码:
#include <isotream.h>
#include<string.h>
#include<stdio.h>

class MyString {
   char cpBody[81];
public :
MyString & operarator++ (int i)
{

 static MyString s ;

 s = *this;  // 这句话什么意思?什么时候需要这样做呢?
*this = (cpBody[0] == '\0') ? *this : (*this)[1]; return s ; //帮忙解释一下这句话的意思。。
void display() {printf("<%s>\n",cpBody);}
friend MyString& operator+(int i ,MyString&s);

}





[ 本帖最后由 avator123 于 2011-12-31 12:44 编辑 ]
6 回复
#2
lijunbo2011-12-31 13:10
1.this是一个指针,是绑定在自身类对象对象上面的,*this就是指针的解引用。至于为什么这么做,当你定义一个类时,并没有生成类对象,所以无法引用类对象的名字,只能用this来表示。
2.?:是c++中的表达式。格式为:cond?expr1:expr2;含义:首先计算cond条件表达式的值,如果为真,则执行expr1,否则执行expr2.
*this = (cpBody[0] == '\0') ? *this : (*this)[1]; return s ;这句话意思是如果数组cpBody的首个元素等于空字符,则*this=*this,也就不变,如果首个元素不为空,*this=(*this)[1],return s;是下一条语句,你完全可以将它单独写为一行,这样更清楚
ps:这个程序写的有点乱,不太符合c++标准。用了很多c的格式

[ 本帖最后由 lijunbo 于 2011-12-31 13:17 编辑 ]
#3
lz10919149992011-12-31 14:06
s = *this; // 调用s的operator=,由于没有显示定义,所以这里调用的是编译器生成的,默认执行位拷贝。
*this = (cpBody[0] == '\0') ? *this : (*this)[1]; return s ; // 这句明显有错误,没有为MyString定义operator[]。

这个类想用后缀++来移动cpBody的首部指针,不过代码是乱写的,我需要我帮你写一个吗?
#4
hellovfp2011-12-31 14:21
楼上的写一个示例一下吧。
#5
lz10919149992011-12-31 14:37
程序代码:
#include <iostream>
#include <cstring>

class MyString {
public:
   MyString(const char* cp): beg(text) {
      std::strcpy(beg, cp);
   }

   MyString& operator++(int) {
      ++beg;
      return *this;
   }

   void display() const {
      std::cout << "<" << beg << ">" << std::endl;
   }
private:
   char text[81];
   char* beg;
};

int main() {
   MyString ms("Hello, Hello, Hello, C Plus Plus");
   ms.display();
   ms++;
   ms.display();
   ms++;ms++;ms++;
   ms.display();
}

/* Output:
<Hello, Hello, Hello, C Plus Plus>
<ello, Hello, Hello, C Plus Plus>
<o, Hello, Hello, C Plus Plus>

Process returned 0 (0x0)   execution time : 0.406 s
Press any key to continue.
*/
#6
烟雾中的迷茫2011-12-31 17:15
解释够详细了…呵呵,简单的说就是该对象本身的指针
#7
avator1232011-12-31 17:45
*this = (cpBody[0] == '\0') ? *this : (*this)[1]; return s ; //(*this) = (*this)[1] 是什么意思?
1