friend class member function must use "inline" ?

here's the overview of the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// file name -- "tv.h"
class Tv;  // forward declaration

class Remote {
public:
void voulmeDown(Tv& t);
}

class Tv {
private:
  int volume;
public:
  friend void Remote::volumeDown(Tv& t);
  void volumleDown() { --volume; }
}

// put Remote member function here, because it calls Tv member function
inline 


when I omit the "inline", the compiler says "multiple definition of`Remote::volumeDown(Tv&)".
It's so weird that when I put the
void Remote::volumeDown(Tv& t) { t.volumeDown(); }
in a implementation file without "inline", it works.
have to use the keyword inline? why ?

here's another question:
assume that Tv class has a function voldown, what's the difference between use bool or void as return type, which one is better?
1
2
3
4
5
6
7
8
bool Tv::voldown() {
	if(volume > 0) {
		--volume;
		return true;
	} else {
		return false;
	}
}


1
2
3
4
void Tv::voldown() {
	if(volume > 0)
	    --volume;
}
Last edited on
void Tv::voldown() is better.
If you want to check (volume > 0), make new function
inline int volget() {return volume;}
then check the returning (int) value instead.
I write a code to test:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// filename : test.h

#include <iostream>
using namespace std;

class ONE;

class TWO
{
public:
  void print(ONE& x);
};

class ONE
{
  int a, b;
  friend void TWO::print(ONE& x);
public:
  ONE() : a(1), b(2) { }
  // void print();  if no function in ONE, it just fine
};

void TWO::print(ONE& x)
{
  cout << "a is " << x.a << endl;
  cout << "b is " << x.b << endl;
}


in main(), I write like this:
1
2
3
4
5
6
7
#include "new_test.h"
int main()
{
  ONE xobj;
  TWO yobj;
  yobj.print(xobj);
}


It's fine, just ok.
but if I add a function in the class ONE, then it won't work.
you have to add "inline" before the defintion of
void TWO::print(ONE& x)
, why ??
closed account (zb0S216C)
You're missing a semi-colon after the closing brace of "Tv". Without it, the compiler assumes "inline" is part of an function declaration. Note that declarations are allowed between the closing brace and the semi-colon.

1
2
3
struct ...
{
} /* Declarations are allowed here */;

Wazzak
All function definitions in header files must be inline functions. Those defined within the class definition are implicitly inline. Those outside the class definition must be explicitly inline. The reason for this is that if the header is included in multiple source files, each source file would think it has the definition of the function, violating the one definition rule.
Topic archived. No new replies allowed.